package com.example.score.config;

import com.example.score.service.Impl.AdminServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author shenrui
 * @date 2021/9/26
 * @description 继承WebSecurityConfigurerAdapter，使用spring security
 */
@Configuration
//激活方法上面的注解
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled =true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    private AdminServiceImpl adminService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       // 一般来说security自动开启防御csrf，类似那种ajax post请求就访问不了，可以调用disable方法注销调，当然这不安全。
        http
                .csrf().disable()
                .authorizeRequests()
                // http.permitAll不会绕开springsecurity验证，相当于是允许该路径通过
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 配置登录页面的访问路径
                .loginPage("/admin_login")
                .loginProcessingUrl("/do_admin_login")
                .usernameParameter("adminName")//设置登录请求接口的参数（用户名）
                .passwordParameter("adminPassword")//设置登录请求接口的参数（密码）
                .defaultSuccessUrl("/admin_main",true)
                // 登录路径允许不用验证即可访问
                .permitAll()
                .and()
                // Spring Security已经有登出的方法，这里配置登出也是可以直接访问
                .logout()
                .logoutSuccessUrl("/admin_login")//注销后跳转到哪一个页面
                .permitAll()
                .and()
                //只允许登录一个
                .sessionManagement()
                .maximumSessions(1).expiredUrl("/admin_login");
    }



    //使用BCryptPasswordEncoder进行加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(adminService).passwordEncoder(new BCryptPasswordEncoder());
    }

}
